/**
 * 
 */
package com.heer.RD.projecthour.page;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.apache.wicket.validation.validator.StringValidator;

import com.heer.RD.projecthour.component.DeptChoice;
import com.heer.RD.projecthour.component.StaffChoice;
import com.heer.RD.projecthour.pojo.DepartmentDTO;
import com.heer.RD.projecthour.pojo.UserDeptDTO;
import com.heer.RD.projecthour.pojo.UserInfoDTO;
import com.heer.RD.util.SecurityFacade;
import com.heer.RD.util.SendGmail;
import com.heer.RD.util.UtilsMisc;
import com.heer.joss.persistence.convention.ExpressionUtil;
import com.mysql.jdbc.Util;


/**
 * @author ZhaoZehui
 *
 */
public class SysMngPage extends BasePage {

	public final List<Map> userList = new ArrayList();
	final WebMarkupContainer operPanel = new WebMarkupContainer("operPanel");
	
	/**
	 * 
	 */
	public SysMngPage(PageParameters para) {
		
		final Form f = new Form("thisForm", new CompoundPropertyModel(new ValueMap()));
		
		final AjaxButton deptUpdateButt = new AjaxButton("deptUpdateButt"){
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				
				operPanel.replace(new DeptUpdatePanel("operPanelContent"));
				target.addComponent(operPanel);
			}
		};
		f.add(deptUpdateButt);
		
		
		final WebMarkupContainer deptPanel = new WebMarkupContainer("deptPanel");
		final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), "root");
		depts.setOutputMarkupId(true);
		depts.setMarkupId("depts");
		deptPanel.setOutputMarkupId(true);
		
		final AjaxButton queryUserButt = new AjaxButton("queryUserButt"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				
				userList.clear();	

				String deptId = depts.getModelValue();
				if(StringUtils.isNotBlank(deptId) && !"-1".equals(deptId)) {
					
					userList.addAll(getMainService().getUserDao().queryByCriteria("dept_id in ('"+StringUtils.join(getMainService().getSubDepts(deptId), "','")+"') order by name"));
				}
				else {
				}
				
				operPanel.replace(new UserListPanel("operPanelContent", depts));
				target.addComponent(operPanel);
				
			}
		};
		f.add(queryUserButt);

		OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
			protected void onUpdate(AjaxRequestTarget target) {
			}
		};
		
		depts.add(changeDept);
		deptPanel.add(depts);
        f.add(deptPanel);
		add(f);
		
		operPanel.setOutputMarkupId(true);
		operPanel.add(new UserListPanel("operPanelContent", depts));
		add(operPanel);
		
		
		final WebMarkupContainer sendMailPanel = new WebMarkupContainer("sendMailPanel");
		
		final TextField weekNum = new TextField("weekNum");
		weekNum.setOutputMarkupId(true);
		
		final WebMarkupContainer sentStaffMailPanel = new WebMarkupContainer("sentStaffMailPanel");
		sentStaffMailPanel.setMarkupId("sentStaffMailPanel").setOutputMarkupId(true);
		sentStaffMailPanel.add(new Label("sentStaffMailFeedback"));
		
		//部门工时统计
		final AjaxButton sentDeptMailButt = new AjaxButton("sentDeptMailButt"){
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				
				if(weekNum.getModelObject() != null) {
					String[] dateRange = UtilsMisc.getWeekRange(Calendar.getInstance().get(Calendar.YEAR), Integer.parseInt(weekNum.getModelObject().toString()));
					//先查询出当前的部门管理员
					List<Map<String, String>> deptMngUserList = getMainService().getJdbcTemplate().queryForList("select u.user_id,u.name,u.mail,u.dept_id,d.dept_name from user_info u,department d where u.dept_id=d.dept_id and substring(user_role,3,1) = 1 and u.is_used = 0 and u.dept_id <> 'root'");
					
					StringBuffer msgStr = new StringBuffer("");
					
					for (Map<String, String> deptMngUser : deptMngUserList) {
						String title = "第"+weekNum.getModelObject()+"周["+dateRange[0]+"~"+dateRange[6]+"]部门工时统计";
						
						try {
							
							StringBuffer htmlStr = new StringBuffer("<table>");
							htmlStr.append("<tr style='color:blue;font-weight:bold;'>");
							htmlStr.append("<td colspan='3' align='center'>"+deptMngUser.get("DEPT_NAME")+"_"+title+"</td>");
							htmlStr.append("</tr>");
							
							//该管理员管理的部门
							String[] depts = getMainService().getSubDepts(deptMngUser.get("DEPT_ID"));
							//管理的人员列表
							List<Map<String, String>> mngUserList = getMainService().getJdbcTemplate().queryForList("select user_id,name from user_info u where u.dept_id in ('"+StringUtils.join(depts, "','")+"') order by name");
							
							for (Map<String, String> user : mngUserList) {
								
								htmlStr.append("<tr style='background-color:#660000;color:#FFFFFF;font-weight:bold;'>");
								htmlStr.append("<td colspan='3'><span>"+user.get("NAME")+"</span></td>");
								htmlStr.append("</tr>");
								
								String criteria = "u.user_id = '"+user.get("USER_ID")+"'";
								criteria += " and u.reg_date >= '"+dateRange[0]+"'";
								criteria += " and u.reg_date <= '"+dateRange[6]+"'";
								
								Map paramMap = UtilsMisc.toMap("criteria", criteria);
								String sql = ExpressionUtil.parse(getMainService().getUserProjCostStatSql(), paramMap);
								
								Double userTotalHour = 0.0d;
								List<Map> userProjStatList = getMainService().getJdbcTemplate().queryForList(sql);
								
								for (Iterator iterator = userProjStatList.iterator(); iterator
										.hasNext();) {
									Map projStat = (Map) iterator.next();
									htmlStr.append("<tr>");
									htmlStr.append("<td>").append(projStat.get("PROJ_NAME")).append("</td>");
									htmlStr.append("<td align='right'>").append(UtilsMisc.transHour(projStat.get("HOUR_COST"))).append("天</td>");
									
									//明细
									String detailcriteria = "u.user_id = '"+user.get("USER_ID")+"' and u.project_id = '"+projStat.get("PROJECT_ID")+"'";
									detailcriteria += " and u.reg_date >= '"+dateRange[0]+"'";
									detailcriteria += " and u.reg_date <= '"+dateRange[6]+"'";
									
//									String detailsql = ExpressionUtil.parse(PersonStatPage.userProjCostDetailSql, UtilsMisc.toMap("criteria", detailcriteria));
//									
//									List udList = getMainService().getJdbcTemplate().queryForList(detailsql);
									
									StringBuffer detailStr = new StringBuffer("");
//									StringBuffer detailStr = new StringBuffer("<table id='"+user.get("USER_ID")+"_"+projStat.get("PROJECT_ID")+"' style='display:none;'>");
//									for (Iterator iterator2 = udList.iterator(); iterator2
//											.hasNext();) {
//										Map udMap = (Map) iterator2.next();
//										detailStr.append("<tr>");
//										detailStr.append("<td>").append(udMap.get("REG_DATE")).append("</td>");
//										detailStr.append("<td>").append(udMap.get("HOUR_COST")).append("小时</td>");
//										detailStr.append("<td>").append(udMap.get("REG_MEMO")).append("</td>");
//										detailStr.append("</tr>");
//									}
//									detailStr.append("</table>");
									
									
									htmlStr.append("<td>").append(detailStr).append("</td>");
									htmlStr.append("</tr>");

									userTotalHour += ((Number)projStat.get("HOUR_COST")).doubleValue();
								}
								
								htmlStr.append("<tr>");
								htmlStr.append("<td>合计：</td>");
								htmlStr.append("<td align='right'><b>").append(UtilsMisc.transHour(userTotalHour)).append("天</b></td>");
								htmlStr.append("</tr>");
							}
							htmlStr.append("<tr>");
							htmlStr.append("<td colspan='3' align='center'>"+"部门工时明细请<a href='http://182.48.112.76:888/hour/' target='_blank'>登录系统</a>查看"+"</td>");
							htmlStr.append("</tr>");
							
							
							htmlStr.append("</table>");
//							htmlStr.append("<script>");
//							htmlStr.append("function tog(did) {if(document.getElementById(did).style.display=='none') document.getElementById(did).style.display=''; else document.getElementById(did).style.display='none';}");
//							htmlStr.append("</script>");
							
							new SendGmail().sendSSLMessage(new String[]{deptMngUser.get("MAIL")}, title, htmlStr.toString());
							msgStr.append("["+deptMngUser.get("NAME")+"]发送成功").append("\n\r");
							
						} catch (MessagingException e) {
							e.printStackTrace();
							sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", e.getLocalizedMessage()));
							msgStr.append("["+deptMngUser.get("NAME")+"]发送 错误").append("\n\r");
						}
					
					}
					sentStaffMailPanel.replace(new MultiLineLabel("sentStaffMailFeedback", "第"+weekNum.getModelObject()+"周部门\n\r"+msgStr));
				}
				else {
					sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", "周数不能为空"));
				}
				target.addComponent(sentStaffMailPanel);
				target.appendJavascript("$('#sentStaffMailPanel').show()");
				
			}
		};
		
		//普通员工的工时统计
		final AjaxButton sentStaffMailButt = new AjaxButton("sentStaffMailButt"){
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				
				if(weekNum.getModelObject() != null) {
					String[] dateRange = UtilsMisc.getWeekRange(Calendar.getInstance().get(Calendar.YEAR), Integer.parseInt(weekNum.getModelObject().toString()));
					//查询出普通员工列表
					List<Map<String, String>> userList = getMainService().getJdbcTemplate().queryForList("select u.user_id,u.name,u.mail,u.mail from user_info u,department d where u.dept_id=d.dept_id and substring(user_role,3,1) <> 1 and u.is_used = 0 and u.dept_id <> 'root'");
					
					StringBuffer msgStr = new StringBuffer("");
					
					String title = "第"+weekNum.getModelObject()+"周["+dateRange[0]+"~"+dateRange[6]+"]个人工时统计";
					for (Map<String, String> user : userList) {
						try {
							
							StringBuffer htmlStr = new StringBuffer("<table>");
							htmlStr.append("<tr style='color:blue;font-weight:bold;'>");
							htmlStr.append("<td colspan='3' align='center'>"+user.get("NAME")+"_"+title+"</td>");
							htmlStr.append("</tr>");
							
							
								
							htmlStr.append("<tr style='background-color:#660000;color:#FFFFFF;font-weight:bold;'>");
							htmlStr.append("<td colspan='3'><span>"+user.get("NAME")+"</span></td>");
							htmlStr.append("</tr>");
							
							String criteria = "u.user_id = '"+user.get("USER_ID")+"'";
							criteria += " and u.reg_date >= '"+dateRange[0]+"'";
							criteria += " and u.reg_date <= '"+dateRange[6]+"'";
							
							Map paramMap = UtilsMisc.toMap("criteria", criteria);
							String sql = ExpressionUtil.parse(getMainService().getUserProjCostStatSql(), paramMap);
							
							Double userTotalHour = 0.0d;
							List<Map> userProjStatList = getMainService().getJdbcTemplate().queryForList(sql);
							
							for (Iterator iterator = userProjStatList.iterator(); iterator
									.hasNext();) {
								Map projStat = (Map) iterator.next();
								htmlStr.append("<tr>");
								htmlStr.append("<td>").append(projStat.get("PROJ_NAME")).append("</td>");
								htmlStr.append("<td align='right'>").append(UtilsMisc.transHour(projStat.get("HOUR_COST"))).append("天</td>");
								
								//明细
								String detailcriteria = "u.user_id = '"+user.get("USER_ID")+"' and u.project_id = '"+projStat.get("PROJECT_ID")+"'";
								detailcriteria += " and u.reg_date >= '"+dateRange[0]+"'";
								detailcriteria += " and u.reg_date <= '"+dateRange[6]+"'";
								
//									String detailsql = ExpressionUtil.parse(PersonStatPage.userProjCostDetailSql, UtilsMisc.toMap("criteria", detailcriteria));
//									
//									List udList = getMainService().getJdbcTemplate().queryForList(detailsql);
								
								StringBuffer detailStr = new StringBuffer("");
//									StringBuffer detailStr = new StringBuffer("<table id='"+user.get("USER_ID")+"_"+projStat.get("PROJECT_ID")+"' style='display:none;'>");
//									for (Iterator iterator2 = udList.iterator(); iterator2
//											.hasNext();) {
//										Map udMap = (Map) iterator2.next();
//										detailStr.append("<tr>");
//										detailStr.append("<td>").append(udMap.get("REG_DATE")).append("</td>");
//										detailStr.append("<td>").append(udMap.get("HOUR_COST")).append("小时</td>");
//										detailStr.append("<td>").append(udMap.get("REG_MEMO")).append("</td>");
//										detailStr.append("</tr>");
//									}
//									detailStr.append("</table>");
								
								
								htmlStr.append("<td>").append(detailStr).append("</td>");
								htmlStr.append("</tr>");

								userTotalHour += ((Number)projStat.get("HOUR_COST")).doubleValue();
							}
							
							htmlStr.append("<tr>");
							htmlStr.append("<td>合计：</td>");
							htmlStr.append("<td align='right'><b>").append(UtilsMisc.transHour(userTotalHour)).append("天</b></td>");
							htmlStr.append("</tr>");
							
							htmlStr.append("<tr>");
							htmlStr.append("<td colspan='3' align='center'>"+"个人工时明细请<a href='http://182.48.112.76:888/hour/' target='_blank'>登录系统</a>查看"+"</td>");
							htmlStr.append("</tr>");
							
							
							htmlStr.append("</table>");
	//							htmlStr.append("<script>");
	//							htmlStr.append("function tog(did) {if(document.getElementById(did).style.display=='none') document.getElementById(did).style.display=''; else document.getElementById(did).style.display='none';}");
	//							htmlStr.append("</script>");

							new SendGmail().sendSSLMessage(new String[]{user.get("MAIL")}, title, htmlStr.toString());
							msgStr.append("["+user.get("NAME")+"]发送成功").append("\n\r");
						
						} catch (MessagingException e) {
							e.printStackTrace();
							sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", e.getLocalizedMessage()));
							msgStr.append("["+user.get("NAME")+"]发送 错误").append("\n\r");
						}
					}	
					sentStaffMailPanel.replace(new MultiLineLabel("sentStaffMailFeedback", "第"+weekNum.getModelObject()+"周员工\n\r"+msgStr));
				}
				else {
					sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", "周数不能为空"));
				}
				target.addComponent(sentStaffMailPanel);
				target.appendJavascript("$('#sentStaffMailPanel').show()");
				
			}
		};
		
		//项目工时统计
		final AjaxButton sentProjMailButt = new AjaxButton("sentProjMailButt"){
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				
				if(weekNum.getModelObject() != null) {
					String[] dateRange = UtilsMisc.getWeekRange(Calendar.getInstance().get(Calendar.YEAR), Integer.parseInt(weekNum.getModelObject().toString()));
					
					//查询出部门管理员和项目经理
					List<Map<String, String>> userList = getMainService().getJdbcTemplate().queryForList("select u.user_id,u.name,u.mail,u.dept_id,u.user_role from user_info u where (substring(user_role,3,1) = 1 or substring(user_role,2,1) = 1) and u.is_used = 0 and u.dept_id <> 'root'");
					
					StringBuffer msgStr = new StringBuffer("");
					
					String title = "第"+weekNum.getModelObject()+"周["+dateRange[0]+"~"+dateRange[6]+"]项目工时统计";
					for (Map<String, String> user : userList) {
						try {
							
							StringBuffer htmlStr = new StringBuffer("<table>");
							htmlStr.append("<tr style='color:blue;font-weight:bold;'>");
							htmlStr.append("<td colspan='3' align='center'>"+user.get("NAME")+"_"+title+"</td>");
							htmlStr.append("</tr>");
							
							String userRole = (String)user.get("USER_ROLE");
							String criteria = "(";
							if("1".equals(userRole.substring(2, 3))) {
								criteria += "d.dept_id = '"+user.get("DEPT_ID")+"'";
							}
							else {
								criteria += "1=2";
							}
							if("1".equals(userRole.substring(1, 2))) {
								criteria += " or p.project_id in (select project_id from user_proj where user_id = '"+user.get("USER_ID")+"')";
							}
							else {
								criteria += " or 1=2";
							}
							criteria += ")";
							
							String uhcriteria = "1=1";
//							uhcriteria += " and u.reg_date >= '"+dateRange[0]+"'";
//							uhcriteria += " and u.reg_date <= '"+dateRange[6]+"'";
							
							Map paramMap = UtilsMisc.toMap("uh_criteria", uhcriteria.toString(), "criteria", criteria);

							String sql = ExpressionUtil.parse(getMainService().getProjCostStatSql(), paramMap);
							//每人负责的项目统计（自己部门的项目和自己是项目经理的项目）
							List<Map> mainProjStatList = getMainService().getJdbcTemplate().queryForList(sql);
							
							
							for (Map<String, String> proj : mainProjStatList) {
								
								htmlStr.append("<tr style='background-color:#660000;color:#FFFFFF;font-weight:bold;'>");
								htmlStr.append("<td><span>"+proj.get("PROJ_NAME")+"</span></td>");
								htmlStr.append("<td align='right'>累计"+UtilsMisc.transHour(proj.get("HOUR_COST"))+"人天</td>");
								htmlStr.append("</tr>");
								
								String pcriteria = "(u.project_id = '"+proj.get("PROJECT_ID")+"' or u.project_id in (select project_id from project where father_proid = '"+proj.get("PROJECT_ID")+"'))";
								pcriteria += " and u.reg_date >= '"+dateRange[0]+"'";
								pcriteria += " and u.reg_date <= '"+dateRange[6]+"'";
								
								Map pparamMap = UtilsMisc.toMap("criteria", pcriteria);
								String psql = ExpressionUtil.parse(getMainService().getProjUserCostSql(), pparamMap);
								
								Double userTotalHour = 0.0d;
								List<Map> userProjStatList = getMainService().getJdbcTemplate().queryForList(psql);
								
								for (Iterator iterator = userProjStatList.iterator(); iterator
										.hasNext();) {
									Map userStat = (Map) iterator.next();
									htmlStr.append("<tr>");
									htmlStr.append("<td>").append(userStat.get("NAME")).append("</td>");
									htmlStr.append("<td align='right'>").append(UtilsMisc.transHour(userStat.get("HOUR_COST"))).append("天</td>");
									
									htmlStr.append("</tr>");

									userTotalHour += ((Number)userStat.get("HOUR_COST")).doubleValue();
								}
								
								htmlStr.append("<tr>");
								htmlStr.append("<td>本周合计：</td>");
								htmlStr.append("<td align='right'><b>").append(UtilsMisc.transHour(userTotalHour)).append("人天</b></td>");
								htmlStr.append("</tr>");
							}
							htmlStr.append("<tr>");
							htmlStr.append("<td colspan='3' align='center'>"+"项目工时明细请<a href='http://182.48.112.76:888/hour/' target='_blank'>登录系统</a>查看"+"</td>");
							htmlStr.append("</tr>");
							
							
							htmlStr.append("</table>");
//							htmlStr.append("<script>");
//							htmlStr.append("function tog(did) {if(document.getElementById(did).style.display=='none') document.getElementById(did).style.display=''; else document.getElementById(did).style.display='none';}");
//							htmlStr.append("</script>");

							new SendGmail().sendSSLMessage(new String[]{user.get("MAIL")}, title, htmlStr.toString());
							msgStr.append("["+user.get("NAME")+"]发送成功").append("\n\r");
						
						} catch (MessagingException e) {
							e.printStackTrace();
							sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", e.getLocalizedMessage()));
							msgStr.append("["+user.get("NAME")+"]发送 错误").append("\n\r");
						}
					}	
					sentStaffMailPanel.replace(new MultiLineLabel("sentStaffMailFeedback", "第"+weekNum.getModelObject()+"周员工\n\r"+msgStr));
				}
				else {
					sentStaffMailPanel.replace(new Label("sentStaffMailFeedback", "周数不能为空"));
				}
				target.addComponent(sentStaffMailPanel);
				target.appendJavascript("$('#sentStaffMailPanel').show()");
				
			}
		};
		
		
		
		sendMailPanel.add(weekNum);
		sendMailPanel.add(sentStaffMailPanel);
		sendMailPanel.add(sentDeptMailButt);
		sendMailPanel.add(sentStaffMailButt);
		sendMailPanel.add(sentProjMailButt);
		
		f.add(sendMailPanel);
		
		if(!"zhaozh".equals(getUser().getUserName())) {
			sendMailPanel.setVisible(false);
		}
	}
	
	public UserUpdatePanel getUserUpdatePanel(String id, String userId) {
		return new UserUpdatePanel(id, userId);
	}
	
	protected class DeptUpdatePanel extends Panel {
		
		
		public DeptUpdatePanel(String id) {
			super(id);
			
			
			final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
			feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
			
			final HiddenField deptIdHidden = new HiddenField("deptId");
			deptIdHidden.setOutputMarkupId(true);
			final RequiredTextField deptName = new RequiredTextField("deptName");
			deptName.setOutputMarkupId(true);
			
			final HiddenField fatherIdInput = new HiddenField("fatherId");
			fatherIdInput.setOutputMarkupId(true);
			final RequiredTextField fatherNameInput = new RequiredTextField("fatherName");
			fatherNameInput.setOutputMarkupId(true);
			
			final HiddenField userIdInput = new HiddenField("userId");
			userIdInput.setOutputMarkupId(true);
			final TextField userNameInput = new TextField("userName");
			fatherNameInput.setOutputMarkupId(true);

			final Button addDeptButt = new Button("addDeptButt");
			addDeptButt.setOutputMarkupId(true);
			addDeptButt.setVisible(true);
			final Button updateDeptButt = new Button("updateDeptButt");
			updateDeptButt.setOutputMarkupId(true);
			updateDeptButt.setVisible(false);
			final Button deleteDeptButt = new Button("deleteDeptButt");
			deleteDeptButt.setOutputMarkupId(true);
			deleteDeptButt.setVisible(false);
			
			final StaffChoice staffs = new StaffChoice("staffs");
			staffs.setOutputMarkupId(true);
			staffs.getStaffDirectly(getMainService().getJdbcTemplate(), "1=1 order by name");
			OnChangeAjaxBehavior changeStaff = new OnChangeAjaxBehavior() {
				protected void onUpdate(AjaxRequestTarget target) {

					String userId = staffs.getModelValue();
					if(StringUtils.isNotBlank(userId) && !"-1".equals(userId)) {
						userIdInput.setModel(new Model(userId));
						userNameInput.setModel(new Model(staffs.getStaffName(userId)));
					}
					else {
						userIdInput.setModel(new Model(""));
						userNameInput.setModel(new Model(""));
					}
					target.addComponent(fatherIdInput);
					target.addComponent(fatherNameInput);
				}
				
			};
			staffs.add(changeStaff);
			
			final DeptChoice deptList = new DeptChoice("deptList", getMainService().getJdbcTemplate(), "root");
			deptList.setOutputMarkupId(true);
			
			final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), "root");
			depts.setOutputMarkupId(true);
			OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
				protected void onUpdate(AjaxRequestTarget target) {

					String deptId = depts.getModelValue();
					if(StringUtils.isNotBlank(deptId) && !"-1".equals(deptId)) {
						fatherIdInput.setModel(new Model(deptId));
						fatherNameInput.setModel(new Model(depts.getDeptName(deptId)));
					}
					else {
						fatherIdInput.setModel(new Model(""));
						fatherNameInput.setModel(new Model(""));
					}
					target.addComponent(fatherIdInput);
					target.addComponent(fatherNameInput);
				}
				
			};
			depts.add(changeDept);

			
			final Form deptUpdateForm = new Form("deptUpdateForm", new CompoundPropertyModel(new ValueMap())) {
				protected void onSubmit() {
					
					DepartmentDTO newDept = new DepartmentDTO();
					newDept.setDeptId((String)deptIdHidden.getModelObject());
					newDept.setDeptName((String)deptName.getModelObject());
					newDept.setFatherId((String)fatherIdInput.getModelObject());
					
					if(StringUtils.isBlank(newDept.getDeptId())) {
						getMainService().getDeptDao().create(newDept);
						
//						UserDeptDTO udDto = new UserDeptDTO();
//						udDto.setUserId((String)userIdInput.getModelObject());
//						udDto.setDeptId(newDept.getDeptId());
//						getMainService().getUserDeptDao().create(udDto);
						
						info("新增部门成功");
						
						deptIdHidden.setModel(new Model<String>(""));
						deptName.setModel(new Model<String>(""));
					}
					else {
						getMainService().getDeptDao().update(newDept);
						
//						UserDeptDTO udDto = new UserDeptDTO();
//						udDto.setUserId((String)userIdInput.getModelObject());
//						udDto.setDeptId(newDept.getDeptId());
//						getMainService().getUserDeptDao().removeByCriteria("dept_id = '"+newDept.getDeptId()+"'");
//						getMainService().getUserDeptDao().create(udDto);
						
						info("修改部门成功");
					}
					
					deptList.init(getMainService().getJdbcTemplate(), "root");
					depts.init(getMainService().getJdbcTemplate(), "root");
				}
			};
			final Form deptListForm = new Form("deptListForm", new CompoundPropertyModel(new ValueMap())) {
				protected void onSubmit() {
					//do nothing
				}
			};
			
			final AjaxLink deleteDeptLink = new AjaxLink("deleteDeptLink") {
					
				@Override
				public void onClick(AjaxRequestTarget target) {
					
					if(!"root".equals(deptIdHidden.getModelObject())) {
						getMainService().getDeptDao().remove((String)deptIdHidden.getModelObject());
						
						deptList.init(getMainService().getJdbcTemplate(), "root");
						depts.init(getMainService().getJdbcTemplate(), "root");
						
						target.addComponent(deptListForm);
						
						addDeptButt.setVisible(true);
						updateDeptButt.setVisible(false);
						deleteDeptButt.setVisible(false);
						deptIdHidden.setModel(new Model<String>(""));
						deptName.setModel(new Model<String>(""));
						fatherIdInput.setModel(new Model<String>(""));
						fatherNameInput.setModel(new Model<String>(""));
						userIdInput.setModel(new Model(""));
						userNameInput.setModel(new Model(""));
						
					}
					target.addComponent(deptUpdateForm);
				}
				
			};
			deleteDeptLink.setOutputMarkupId(true);
			
			OnChangeAjaxBehavior selectDept = new OnChangeAjaxBehavior() {
				protected void onUpdate(AjaxRequestTarget target) {

					String deptId = deptList.getModelValue();
					
					if(StringUtils.isNotBlank(deptId) && !"-1".equals(deptId)) {
						deptIdHidden.setModel(new Model(deptId));
						deptName.setModel(new Model(deptList.getDeptName(deptId)));
						String fatherId = getMainService().getFatherId(deptId);
						fatherIdInput.setModel(new Model<String>(fatherId));
						fatherNameInput.setModel(new Model<String>(deptList.getDeptName(fatherId)));
						
						List<UserDeptDTO> udList = getMainService().getUserDeptDao().queryByCriteria("dept_id = '"+deptId+"'");
						if(!CollectionUtils.isEmpty(udList)) {
							userIdInput.setModel(new Model(udList.get(0).getUserId()));
							userNameInput.setModel(new Model(staffs.getStaffName(udList.get(0).getUserId())));
						}
						
						addDeptButt.setVisible(false);
						updateDeptButt.setVisible(true);
						deleteDeptButt.setVisible(true);
					}
					else {
						deptIdHidden.setModel(new Model<String>(""));
						deptName.setModel(new Model<String>(""));
						fatherIdInput.setModel(new Model<String>(""));
						fatherNameInput.setModel(new Model<String>(""));
						userIdInput.setModel(new Model(""));
						userNameInput.setModel(new Model(""));
						
						addDeptButt.setVisible(true);
						updateDeptButt.setVisible(false);
						deleteDeptButt.setVisible(false);
					}
					
					
					target.addComponent(deptUpdateForm);
				}
				
			};
			deptList.add(selectDept);
			
			deptUpdateForm.add(addDeptButt);
			deptUpdateForm.add(updateDeptButt);
			deptUpdateForm.add(deleteDeptButt);
			deptUpdateForm.add(deleteDeptLink);
			
			deptUpdateForm.setOutputMarkupId(true);
			deptUpdateForm.add(feedbackPanel);
			deptUpdateForm.add(depts);
			
			deptUpdateForm.add(fatherIdInput);
			deptUpdateForm.add(fatherNameInput);
			deptUpdateForm.add(deptIdHidden);
			deptUpdateForm.add(deptName);
			
			deptUpdateForm.add(userIdInput);
			deptUpdateForm.add(userNameInput);
			deptUpdateForm.add(staffs);
			
			
			deptListForm.add(new AjaxButton("addDepteButt"){
				@Override
				protected void onSubmit(AjaxRequestTarget target, Form form) {
					
					addDeptButt.setVisible(true);
					updateDeptButt.setVisible(false);
					deleteDeptButt.setVisible(false);
					deptIdHidden.setModel(new Model<String>(""));
					deptName.setModel(new Model<String>(""));
					fatherIdInput.setModel(new Model<String>(""));
					fatherNameInput.setModel(new Model<String>(""));
					
					
					target.addComponent(deptUpdateForm);
				}
			});
			
			deptListForm.add(deptList);
			
			add(deptListForm);
			add(deptUpdateForm);
		}
	}
	
	public class UserUpdatePanel extends Panel {
		
		UserInfoDTO user = new UserInfoDTO();
		
		public UserUpdatePanel(String id, final String userId) {
			super(id);
			
			if(StringUtils.isNotEmpty(userId)) {
				user = (UserInfoDTO)getMainService().getUserDao().findById(userId);
			}
			
			final FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackSpecial");
			feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackSpecialPanel");
			
			Label selectedDate = new Label("selectedDate", "新增用户");
			selectedDate.setMarkupId("selectedDate");
			selectedDate.setOutputMarkupId(true);
			
			if(StringUtils.isNotBlank(user.getUserId())) {
				selectedDate.setDefaultModel(new Model("修改["+user.getName()+"]"));
			}

			final HiddenField userIdHidden = new HiddenField("userIdHidden", new Model<String>(userId));
			
			final HiddenField deptIdInput = new HiddenField("deptId");
			deptIdInput.setOutputMarkupId(true);
			final TextField deptNameInput = new TextField("deptName");
			deptNameInput.setOutputMarkupId(true);
			
			Label loginName = new Label("loginName", user.getUserName());
			
			final TextField xm = new TextField("xm", new Model<String>(user.getName()));
//			xm.add(StringValidator.maximumLength(50));
			final TextField mail = new TextField("mail", new Model<String>(user.getMail()));
//			mail.add(EmailAddressValidator.getInstance());
			
			final PasswordTextField pass = new PasswordTextField("loginPass"); 
			pass.setRequired(false);
			
			final PasswordTextField repass = new PasswordTextField("reLoginPass"); 
			repass.setRequired(false);
			
			
			final Form userUpdateForm = new Form("userUpdateForm", new CompoundPropertyModel(new ValueMap())) {
				protected void onSubmit() {
				}
			};
			
			userUpdateForm.setOutputMarkupId(true);
			userUpdateForm.add(feedbackPanel);
			userUpdateForm.add(selectedDate);
			userUpdateForm.add(userIdHidden);
			userUpdateForm.add(loginName);
			
			userUpdateForm.add(new AjaxButton("submitButt"){

				@Override
				protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
					UserInfoDTO newUser = new UserInfoDTO();
					newUser.setDeptId((String)deptIdInput.getModelObject());
					newUser.setName((String)xm.getModelObject());
					newUser.setMail((String)mail.getModelObject());
					newUser.setUserId((String)userIdHidden.getModelObject());
					newUser.setUpdateDate(UtilsMisc.getCurrTimeStr());
					
					if (StringUtils.isBlank(newUser.getName())) {
						error("姓名不能为空!");
					}
					else if (StringUtils.isBlank(newUser.getDeptId())) {
						error("部门不能为空!");
					}
					else if (StringUtils.isBlank(newUser.getMail()) || !UtilsMisc.checkEmail(newUser.getMail())) {
						error("邮箱不能为空且要符合格式!");
					}
					else {
					
						if (StringUtils.isNotBlank((String)pass.getModelObject())) {
							if (!pass.getModelObject().equals(repass.getModelObject())) {
								error("两次密码输入不一致!");
							}
							else {
								newUser.setUserPwd((String)pass.getModelObject());
								getMainService().getUserDao().update(newUser);
								info("用户信息和密码修改成功");
							}
						}
						else {
							getMainService().getUserDao().update(newUser);
							info("用户信息修改成功");
						}
					}
					target.addComponent(feedbackPanel);
					
				}
				
			});
			
			final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), "root");
			depts.setOutputMarkupId(true);
			OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
				protected void onUpdate(AjaxRequestTarget target) {

					String deptId = depts.getModelValue();
					if(StringUtils.isNotBlank(deptId) && !"-1".equals(deptId)) {
						deptIdInput.setModel(new Model(deptId));
						deptNameInput.setModel(new Model(depts.getDeptName(deptId)));
					}
					else {
						deptIdInput.setModel(new Model(""));
						deptNameInput.setModel(new Model(""));
					}
					target.addComponent(deptIdInput);
					target.addComponent(deptNameInput);
				}
				
			};
			depts.add(changeDept);
			deptIdInput.setModel(new Model(user.getDeptId()));
			deptNameInput.setModel(new Model(depts.getDeptName(user.getDeptId())));
			
			userUpdateForm.add(depts);
			
			userUpdateForm.add(deptIdInput);
			userUpdateForm.add(deptNameInput);
			userUpdateForm.add(xm);
			userUpdateForm.add(mail);
			
			userUpdateForm.add(pass);
			userUpdateForm.add(repass);
			
			add(userUpdateForm);
		}
	}
	
	protected class UserListPanel extends Panel {
		
		final WebMarkupContainer userListPanel = new WebMarkupContainer("userListPanel");

		public UserListPanel(String id, final DeptChoice depts) {
			super(id);
			
			final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
			feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
			
			final Label selectedDate = new Label("selectedDate", "用户列表");
			selectedDate.setMarkupId("selectedDate");
			selectedDate.setOutputMarkupId(true);;
			
			final Form userMngForm = new Form("userMngForm", new CompoundPropertyModel(new ValueMap())) {
				protected void onSubmit() {
				}
			};
			
			userListPanel.setOutputMarkupId(true);
			userListPanel.add(new ListView("userList", userList) {
				protected void populateItem(final ListItem item) {
					final UserInfoDTO userInfo = (UserInfoDTO)item.getModelObject();
					item.add(new Label("idx", (item.getIndex()+1)+""));
					item.add(new Label("userName", userInfo.getUserName()));
					item.add(new Label("xm", userInfo.getName()));
//					item.add(new Label("mail", userInfo.getMail()));
					item.add(new Label("dept", depts.getDeptName(userInfo.getDeptId())));
					item.add(new Label("isUsed", userInfo.getIsUsed()==0?"有效":"无效"));
					
					item.add(new AjaxButton("updateButt"){

						protected void onSubmit(AjaxRequestTarget target,Form form) {
							operPanel.replace(new UserUpdatePanel("operPanelContent", userInfo.getUserId()));
							target.addComponent(operPanel);
						}
					});
					item.add(new AjaxSubmitLink("setInvalidLink") {

						@Override
						protected void onSubmit(AjaxRequestTarget target,Form form) {
							
							getMainService().getJdbcTemplate().update("update user_info set is_used = '1' where user_id = '"+userInfo.getUserId()+"'");
							userInfo.setIsUsed(1);
							target.addComponent(userListPanel);
						}

					});
					item.add(new AjaxSubmitLink("setValidLink") {

						@Override
						protected void onSubmit(AjaxRequestTarget target,Form form) {
							
							getMainService().getJdbcTemplate().update("update user_info set is_used = '0' where user_id = '"+userInfo.getUserId()+"'");
							userInfo.setIsUsed(0);
							target.addComponent(userListPanel);
						}

					});
					item.add(new AjaxSubmitLink("delLink") {

						@Override
						protected void onSubmit(AjaxRequestTarget target,Form form) {
							
							getMainService().getUserDao().remove(userInfo.getUserId());
							getMainService().getUserProjDao().removeByCriteria("user_id = '"+userInfo.getUserId()+"'");
							
							userList.remove(userInfo);
							target.addComponent(userListPanel);
						}
					});
					
					final String userRole = userInfo.getUserRole();
					
					item.add(new AjaxCheckBox("isStaff", new Model<Boolean>(SecurityFacade.checkRole(userRole, 1))) {
						
						@Override
						protected void onUpdate(AjaxRequestTarget target) {
							String ur = getLatestUserRole(userInfo.getUserId());
							updateUserRole(((getModel().getObject())?"1":"0")+ur.substring(1), userInfo.getUserId());
						}
					});
					item.add(new AjaxCheckBox("isPM", new Model<Boolean>(SecurityFacade.checkRole(userRole, 2))) {
						
						@Override
						protected void onUpdate(AjaxRequestTarget target) {
							String ur = getLatestUserRole(userInfo.getUserId());
							updateUserRole(ur.substring(0,1)+((getModel().getObject())?"1":"0")+ur.substring(2), userInfo.getUserId());
							
						}
					});
					item.add(new AjaxCheckBox("isManager", new Model<Boolean>(SecurityFacade.checkRole(userRole, 3))) {
						
						@Override
						protected void onUpdate(AjaxRequestTarget target) {
							String ur = getLatestUserRole(userInfo.getUserId());
							updateUserRole(ur.substring(0,2)+((getModel().getObject())?"1":"0")+ur.substring(3), userInfo.getUserId());
							
						}
					});
					item.add(new AjaxCheckBox("isAdmin", new Model<Boolean>(SecurityFacade.checkRole(userRole, 4))) {
						
						@Override
						protected void onUpdate(AjaxRequestTarget target) {
							String ur = getLatestUserRole(userInfo.getUserId());
							updateUserRole(ur.substring(0,3)+((getModel().getObject())?"1":"0"), userInfo.getUserId());
						}
					});
					
				}
				
			});
			userMngForm.add(userListPanel);
			
			userMngForm.add(feedbackPanel);
			userMngForm.add(selectedDate);
			add(userMngForm);
		}
		
		private void updateUserRole(String userRole, String userId) {
			getMainService().getJdbcTemplate().update("update user_info set user_role = ? where user_id = ?", new Object[]{userRole, userId});
		}
		private String getLatestUserRole(String userId) {
			return (String)getMainService().getJdbcTemplate().queryForObject("select user_role from user_info where user_id = ?", new Object[]{userId}, String.class);
		}
		
	}
	
}
